import 'package:card_swiper/card_swiper.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:wanandroid_flutter/controller/home_controller.dart';

import '../widgets/article_item.dart';

/// 主页
class HomePage extends StatelessWidget {
  HomePage({super.key});

  final HomeController homeCtr = Get.put(HomeController());


  @override
  Widget build(BuildContext context) {
    return EasyRefresh.builder(
        //嵌套NestedScrollView的时候推荐使用这个MaterialHeader
        header: const MaterialHeader(clamping: true),
        controller: homeCtr.controller,
        onRefresh: homeCtr.refreshRequest,
        onLoad: homeCtr.loadMoreRequest,
        childBuilder: (context, physics) {
          return NestedScrollView(
              physics: physics,
              headerSliverBuilder:
                  (BuildContext context, bool innerBoxIsScrolled) {
                return <Widget>[
                  SliverToBoxAdapter(child: Obx(() => topBanner()))
                ];
              },
              body: Obx(() => articlesList(physics)));
        });
  }

  Widget topBanner() {
    return SizedBox(
        height: 220,
        child: Swiper(
            itemCount: homeCtr.bannerList.length,
            pagination: const SwiperPagination(),
            autoplay: true,
            loop: true,
            onTap: (int index) {
              var item = homeCtr.articleList[index];
              Fluttertoast.showToast(msg: item.link);
            },
            itemBuilder: (context, index) {
              return Image.network(
                  homeCtr.bannerList[index].imagePath.toString(),
                  fit: BoxFit.fill);
            }));
  }

  Widget articlesList(ScrollPhysics physics) {
    return ListView.builder(
        physics: physics,
        shrinkWrap: true,
        padding: const EdgeInsets.only(top: 5),
        itemCount: homeCtr.articleList.length,
        itemBuilder: (context, index) {
          var item = homeCtr.articleList[index];
          return ArticleItem(item: item,);
        });
  }

}
